package com.web.portal.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean subject = new ShiroFilterFactoryBean();
        subject.setSecurityManager(securityManager);

        Map<String, String> map = new LinkedHashMap<>();

//        授权
        map.put("/admin/**", "perms[admin]");
        // 设置 /user/ 下面的所有请求,只有认证过才能访问
        subject.setFilterChainDefinitionMap(map);

        //拦截时 会跳到登录页
        // 设置登录的请求
        subject.setLoginUrl("/401");
        // 未授权
        subject.setUnauthorizedUrl("/noauth");

        // 共同
        map.put("/article/**", "anon");
        map.put("/honors/**", "anon");

        map.put("/user/login", "anon");
        // 查询
        map.put("/category/**", "anon");
        map.put("/label_artice/**", "anon");
        map.put("/label_info/**", "anon");
        map.put("/project/**", "anon");

        //        swagger
        //放行Swagger2页面，需要放行这些
        map.put("/swagger-ui.html", "anon");
        map.put("/swagger/**", "anon");
        map.put("/webjars/**", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/**", "anon");
        map.put("/static/**", "anon");
        map.put("/csrf", "anon");

        Map<String, Filter> filterMap = new HashMap<>(1);
        filterMap.put("jwt", new JwtFilter());
        subject.setFilters(filterMap);
        map.put("/**", "jwt");
        subject.setFilterChainDefinitionMap(map);

        return subject;
    }

    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurity(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setRealm(userRealm);
        return defaultSecurityManager;
    }

    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}
